package com.inet.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.Log;

/**
 * 图片相关操作的工具类
 */
public class BitmapUtils {
	/**
	 * 从字节数组中按照用户的参数要毿
	 * 压缩图片⾿
	 * @param bytes   源字节数繿
	 * @param width   压缩后的图片宽度
	 * @param height  压缩后的图片高度
	 * @return
	 */
	public static Bitmap loadBitmap(byte[] bytes, int width, int height){
		Options opts=new Options();
		//仅仅加载图片的边界属性
		opts.inJustDecodeBounds=true;
		BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
		//获取原始的宽度与高度
		int w=opts.outWidth/width;
		int h=opts.outHeight/height;
		int scale=w>h ? w : h;
		opts.inSampleSize=scale;
		//不仅仅加载边界属性
		opts.inJustDecodeBounds=false;
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
	}
	
	public static byte[] getByte(File file) throws Exception {   
		        byte[] bytes = null;   
		        if (file != null) {   
		            InputStream is = new FileInputStream(file);   
		           int length = (int) file.length();   
		            if (length > Integer.MAX_VALUE) // // 当文件的长度超过了int的最大值   
		            {   
		                Log.i("xxx","this file is max "); 
		                return null;   
		            }   
		            bytes = new byte[length];   
		            int offset = 0;   
		          int numRead = 0;   
		            while (offset < bytes.length   
		                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {   
		                offset += numRead;   
		            }   
		            //  // 如果得到的字节长度和file实际的长度不同就可能出错了 
		            if (offset < bytes.length) {   
		            	Log.i("xxx","file length is error");
		                return null;   
		            }   
		            is.close();   
		        }   
		        return bytes;   
		    }  

	/**  
	  * 保存文件  
	  * @param bm  
	  * @param fileName  
	  * @throws IOException  
	  */    
	 public static void saveFile(Bitmap bm, String fileName) throws IOException {   
//	 String path = getSDPath() +"/revoeye/";       
//	     File dirFile = new File(path);    
//	    if(!dirFile.exists()){    
//	        dirFile.mkdir();    
//	    }    
	    File myCaptureFile = new File(fileName);    
	    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));    
	     bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);    
	    bos.flush();    
	    bos.close();    
	 }  

}




